// page/tabBar/delivery/delivery.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navData: [{
        name: '全部订单',
        type: ''
      },
      {
        name: '待付款',
        type: 'WAITPAY'
      },
      {
        name: '待发货',
        type: 'WAITSEND'
      },
      {
        name: '待收货',
        type: 'WAITRECEIVE'
      },
      {
        name: '已完成',
        type: 'FINISH'
      }
    ],
    page: 1,
    isEnd: false,
    currentData: 0,
    receiving: true,
    orders: [],
    reasons: [
      '订单不能及时送达',
      '操作有误（商品、地址等选错）',
      '重复下单/误下单',
      '其他渠道价格更低',
      '该商品降价了',
      '不想买了'
    ],
    submit:1,
    userInfoAuthorization: true,
    canIUseGetUserProfile: false,
    throttle2: true,
  },

  //点击列表按钮
  navClick(e) {
    const that = this;
    if (e.currentTarget.dataset.currentdata != that.data.currentData) {
      that.setData({
        isEnd: false,
        page: 1
      })
    }
    that.setData({
      currentData: e.currentTarget.dataset.currentdata,
    })
    that.getOrderList();
  },

  //去自提
  todeliveryBnt(e){
    let id = e.currentTarget.dataset.id;
    const that = this;
    let json = {
      token: app.globalData.token,
      order_id: id
    }
    that.setData({
      hiddenLoading: false
    })
    let jsonData = app.utils.getSignData(json);
    app.utils.post(app.api.reqUrls.getTheCode, jsonData).then(res => {
      if (res.status == 1) {
        wx.navigateTo({
          url: '/page/details/pages/deliveryCode/deliveryCode?id=' + id,
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
      }
      that.setData({
        hiddenLoading: true
      })
    })
  },

  //立即评价
  toEvaluate() {
    wx.navigateTo({
      url: '/page/detail/pages/myComments/myComments?index=1',
    })
  },

  doPay(e) { //立即支付
    const that = this;
    let submit = that.data.submit;
    if (submit == 1) {
      submit += 1;
      that.setData({
        submit: submit
      })
      setTimeout(() => {
        that.setData({
          submit: 1
        })
      }, 2000)
      let money = e.currentTarget.dataset.money;
      let sn = e.currentTarget.dataset.sn;
      let json = {
        token: app.globalData.token,
        trade_type: "JSAPI",
        master_order_sn: sn,
        account: money
      }
      let jsonData = app.utils.getSignData(json);
      app.utils.post(app.api.reqUrls.doPay, jsonData).then(res => {
        if (res.status == 1) {
          console.log("支付信息：", res.result)
          wx.requestPayment({ // 调取支付
            timeStamp: res.result.timeStamp.toString(),
            nonceStr: res.result.nonceStr,
            package: res.result.package,
            signType: res.result.signType,
            paySign: res.result.sign,
            success(res) {
              if (res.errMsg == "requestPayment:ok") {
                that.getOrderList();
                app.getInfo(app.globalData.token)
              } else {
                throw res.errMsg;
              }
            },
            fail(res) {
              console.log(res)
            }
          })

        } else {
          throw res.msg
        }
      }).catch(err => {
        app.showInfo(err.toString())
      })
    }
  },

  toGoodsDetail(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/detail/pages/details/details?id=${id}`,
    })
  },
  // 去申请售后
  toAfterSale(e) {
    console.log(e)
    wx.navigateTo({
      url: `/page/detail/pages/applyAfterSale/applyAfterSale?orderid=${e.currentTarget.dataset.orderid}&order_sn=${e.currentTarget.dataset.order_sn}`
    })
  },


  // 取消订单
  cancelOrder(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    if (that.data.orders[index].order_status_detail == "待支付") {
      let json = {
        token: app.globalData.token,
        order_id_sn: that.data.orders[index].order_id + '=' + that.data.orders[index].master_order_sn
      }
      let jsonData = app.utils.getSignData(json);

      wx.showModal({
        content: '是否取消该订单',
        confirmText: '确定',
        confirmColor: '#ff5151',
        success(e) {
          if (e.confirm) {
            app.utils.post(app.api.reqUrls.cancelOrder, jsonData).then(res => {
              if (res.status == 1) {
                app.showInfo(res.msg)
                that.getOrderList();
              } else {
                throw res.msg
              }
            }).catch(err => {
              app.showInfo(err.toString())
            })
          }
        }
      })
    } else {

      wx.showActionSheet({
        itemList: that.data.reasons,
        success(res) {
          let json = {
            token: app.globalData.token,
            order_id: that.data.orders[index].order_id,
            consignee: that.data.orders[index].children[0].consignee,
            mobile: that.data.orders[index].children[0].mobile,
            user_note: that.data.reasons[res.tapIndex],
            is_json: 1
          }
          let jsonData = app.utils.getSignData(json);

          wx.showModal({
            content: '是否取消该订单',
            confirmText: '确定',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {
                that.setData({
                  hiddenLoading: false
                })
                app.utils.post(app.api.reqUrls.cancelPaidOrder, jsonData).then(res => {
                  console.log(res)
                  that.setData({
                    hiddenLoading: true
                  })
                  if (res.status == 1) {
                    app.showInfo(res.msg);
                    that.getOrderList();
                  } else {
                    throw res.msg
                  }
                }).catch(err => {
                  app.showInfo(err.toString());
                  that.setData({
                    hiddenLoading: true
                  })
                })
              }
            }
          })
        },
        fail(res) {
          console.log(res.errMsg)
        }
      })
    }
  },

  toLogistics(e) { // 查看物流
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/page/detail/pages/logistics/logistics?id=${id}`,
    })
  },
//确认收货
  orderConfirm(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    let json = {
      token: app.globalData.token,
      order_id: id
    }
    let jsonData = app.utils.getSignData(json)
    that.setData({
      hiddenLoading: false
    })
    wx.showModal({
      content: '是否确认收货',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(e) {
        if (e.confirm) {
          app.utils.post(app.api.reqUrls.orderConfirm, jsonData).then(res => {
            that.setData({
              hiddenLoading: true
            })
            console.log(res)
            if (res.status == 1) {
              wx.navigateTo({
                url: '/page/detail/pages/myComments/myComments?index=1',
              })
            } else {
              throw res.msg
            }
          }).catch(err => {
            app.showInfo(err.toString());
            that.setData({
              hiddenLoading: true
            })
          })
        } else {
          that.setData({
            hiddenLoading: true
          })
        }
      },
      fail() {
        that.setData({
          hiddenLoading: true
        })
      }
    })
  },
  // 订单详情
  toDetail(e) { 
    const that = this;
    let sn = e.currentTarget.dataset.sn;
    let id = e.currentTarget.dataset.id;
    let storeid = e.currentTarget.dataset.storeid;
    wx.navigateTo({
      url: `/page/detail/pages/orderDetails/orderDetails?sn=${sn}&id=${id}&store_id=${storeid}`,
    })
  },

  // 再来一单
  toBuyAgain(e) {
    const that = this;
    let json = {
      token: app.globalData.token,
      order_id_sn: e.currentTarget.dataset.id + '=' + e.currentTarget.dataset.order_sn
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.another_order, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        wx.showModal({
          content: res.msg.toString(),
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {
            if (e.confirm) {
              wx.switchTab({
                url: '/page/tabBar/cart/cart',
              })
            }
          }
        })
      } else if (res.status == 0) {
        app.showInfo(res.msg.toString())
      } else {
        throw res.msg
      }
    }).catch(err => {
      if (res.status != undefined) {
        app.showInfo(err.toString());
      } else {
        console.log('服务器错误')
      }
    })
  },

  getOrderList() {
    const that = this;
    let json = {
      token: app.globalData.token,
      type: that.data.navData[that.data.currentData].type || '',
      p: 1
    }
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.getZtOrderList, app.utils.getSignData(json)).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        // console.log(res.result)
        if (res.result != null && res.result != []) {
          res.result.forEach(item => {
            if(item.children && item.children.length >=2){
               item.phonestate=0;
               item.doublephoone = [];
               item.children.forEach(items =>{
                if(items.store.store_type == 1){
                  item.doublephoone.push( '客服：' + items.store.store_phone);
                }
                 if(items.store.store_type == 0){
                  item.doublephoone.push('客服：'  +  items.store.store_phone);
                  item.store_newid =  items.store.store_id;
                }
                if(items.store.store_type == 2){
                  item.doublephoone.push('客服：'  +  items.store.store_phone);
                  item.store_newid =  items.store.store_id;
                }
              })
            }else{
              if(item.children){
                item.children.forEach(items =>{
                  if(items.store.store_type == 1){
                    item.phonestate = 1;
                    item.crdphone =  items.store.store_phone;
                    item.store_newid =  0;
                  }else if(items.store.store_type == 0){
                     item.phonestate = 2;
                     item.jrdphone =  items.store.store_phone;
                     item.store_newid =  items.store.store_id;
                  }else if(items.store.store_type == 2){
                    item.phonestate = 3;
                    item.qiyephone =  items.store.store_phone;
                    item.store_newid =  items.store.store_id;
                 }
                })
              }

            }
            if(item.children){
            item.children.forEach(item =>{
              app.getImg(item.order_goods);
              item.count_goods = item.order_goods.length  
            })
          }
          })
        }
        that.setData({
          orders: res.result
        })
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },



  getMoreOrderList() {
    const that = this;
    if (that.data.isEnd) {
      return
    }
    let json = {
      token: app.globalData.token,
      type: that.data.navData[that.data.currentData].type || '',
      p: that.data.page + 1
    }
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.getZtOrderList, app.utils.getSignData(json)).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (res.result != null && res.result != '') {
          res.result.forEach(item => {
            if(item.children && item.children.length >=2){
              item.phonestate=0;
              item.doublephoone = [];
              item.children.forEach(items =>{
               if(items.store.store_type == 1){
                 item.doublephoone.push( '客服：' + items.store.store_phone);
               }
                if(items.store.store_type == 0){
                 item.doublephoone.push('客服：'  +  items.store.store_phone);
                 item.store_newid =  items.store.store_id;
               }
               if(items.store.store_type == 2){
                item.doublephoone.push('客服：'  +  items.store.store_phone);
                item.store_newid =  items.store.store_id;
              }
             })
           }else{
             if(item.children){
              item.children.forEach(items =>{
                if(items.store.store_type == 1){
                  item.phonestate = 1;
                  item.crdphone =  items.store.store_phone;
                  item.store_newid =  0;
                }else if(items.store.store_type == 0){
                   item.phonestate = 2;
                   item.jrdphone =  items.store.store_phone;
                   item.store_newid =  items.store.store_id;
                }else if(items.store.store_type == 2){
                  item.phonestate = 3;
                  item.qiyephone =  items.store.store_phone;
                  item.store_newid =  items.store.store_id;
               }
              })
             }

           }
           if(item.children){
            item.children.forEach(item =>{
              app.getImg(item.order_goods);
              item.count_goods = item.order_goods.length
            })
           }
          })
          that.setData({
            orders: [...that.data.orders, ...res.result],
            page: that.data.page + 1
          })
        } else {
          that.setData({
            isEnd: true
          })
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 1000
          })
        }
      } else {
        throw res.msg
      }
    }).catch(err => {
      app.showInfo(err.toString())
      that.setData({
        hiddenLoading: true
      })
    })
  },

  //联系客服
  servicePhone(e) {
    if(e.currentTarget.dataset.tel){
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.tel //仅为示例，并非真实的电话号码
      })
    }else{
      wx.showToast({
        title: '当前店铺没有留下联系方式',
        icon:"none"
      })
    }
  },
//联系客服
popSelect:function(e) {

  wx.showActionSheet({
    itemList: e.currentTarget.dataset.tel,
    success: function (res) {
      console.log(res.tapIndex);
    var str =  e.currentTarget.dataset.tel[res.tapIndex];
    var  str_new = str.substring(6,str.length) //取电话字符
      console.log(str_new);
    wx.makePhoneCall({
       phoneNumber: str_new //仅为示例，并非真实的电话号码
      })
    }
  })
},

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;
    if (options.where) {
      that.setData({
        currentData: options.where
      })
    }
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },

  onShow() {
    const that = this;
    that.setData({
      isEnd: false,
      page: 1
    })
    clearTimeout(that.data.throttle2);
    app.utils.login().then(res => {
      that.setData({
        code: res.code
      })
    })
    that.setData({
      userInfoAuthorization: app.globalData.userInfoAuthorization,
    })

    if (that.data.userInfoAuthorization) {
      let throttle2 = setTimeout(() => { // 添加节流
        that.getOrderList();
      }, 400)
      that.setData({
        throttle2
      })
    } else {
      wx.nextTick(() => {
        that.setData({
          hiddenLoading: true,
        })
        wx.stopPullDownRefresh()
      })
    }

    
  },

  onReachBottom() {
    const that = this;
    that.getMoreOrderList();
  },
 // 回到首页
 toHome() {
  const that = this;
  wx.switchTab({
    url: '/page/tabBar/index/index',
  })
},
  getUserProfile(e) {
    const that = this;
    if (this.data.canIUseGetUserProfile) {
      wx.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log("logwxsucess", res);
          that.doLogin(e, res.userInfo);
        },
        fail: res => {
          console.log("logwxloginres", res);
          wx.hideLoading();
        }
      });
    } else {
      that.doLogin(e);
    }
  },

  doLogin(e, proFileUserInfo = null) { //旧的登陆代码
    const that = this;
    //原来的登陆代码逻辑，在旧的getUserInfo代码处新增判断：
    wx.getUserInfo({
      success: function (res) {
        /* begin 下面3行是新增的判断，代表userInfo已经通过wx.getUserProfile获取过获取过*/
        if (proFileUserInfo) {
          res.userInfo = proFileUserInfo;
        }
        let json = {
          oauth: "miniapp",
          nickname: res.userInfo.nickName,
          head_pic: res.userInfo.avatarUrl,
          sex: res.userInfo.gender,
          versionCode: app.globalData.systemInfo.SDKVersion,
          code: that.data.code,
          iv: res.iv,
          encryptedData: res.encryptedData,
          signature: res.signature
        }

        let jsonData = app.utils.getSignData(json); // 添加签名

        that.setData({
          hiddenLoading: false
        })
        app.utils.post(app.api.reqUrls.login, jsonData).then(res => {
          that.setData({
            hiddenLoading: true
          })
          if (res == 999) {
            return
          }
          if (res.status == 1) {
            app.globalData.isfirstnewuser = true;
            app.globalData.userInfo = res.result;
            app.globalData.userInfoAuthorization = true;
            that.setData({
              userInfo: res.result,
              userInfoAuthorization: true
            })
            wx.setStorageSync("token", res.result.token);
            wx.setStorageSync("userInfo", res.result);
            app.globalData.token = res.result.token;
            app.globalData.userInfo = res.result;
            // 判断是否渠道会员，type == 1是渠道会员
            if (app.globalData.userInfo) {
              that.setData({
                type: app.globalData.userInfo.type
              })
            }
            that.getOrderList();
            app.getCartCount();
            if (res.result.mobile == '') {
              wx.redirectTo({
                url: '/page/tabBar/bindphone/bindphone',
              })
            }
          } else {
            throw res.msg
          }
        }).catch(err => {
          if (err != undefined) {
            app.showInfo(err.toString())
          } else {
            console.log('服务器错误')
          }
          that.setData({
            hiddenLoading: true
          })
        })

        /* end */
      }
    });

  },
})

